package com.example.socialapp.ui.recommendation

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.BookmarkBorder
import androidx.compose.material.icons.filled.EmojiEvents
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Lightbulb
import androidx.compose.material.icons.filled.LocalFireDepartment
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.NewReleases
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.Whatshot
import androidx.compose.material.icons.outlined.Comment
import androidx.compose.material.icons.outlined.Share
import androidx.compose.material.Chip
import androidx.compose.material.ChipDefaults
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import java.util.Locale
import kotlin.math.absoluteValue
import kotlin.random.Random

/**
 * 内容推荐界面
 *
 * @param onNavigateBack 返回上一界面回调
 * @param onNavigateToUserProfile 导航到用户资料界面回调
 * @param onNavigateToPostDetail 导航到动态详情界面回调
 * @param onNavigateToTopic 导航到话题详情界面回调
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RecommendationScreen(
    onNavigateBack: () -> Unit,
    onNavigateToUserProfile: (String) -> Unit = {},
    onNavigateToPostDetail: (String) -> Unit = {},
    onNavigateToTopic: (String) -> Unit = {}
) {
    // 在实际应用中应从ViewModel获取推荐内容
    val recommendedContent = remember { generateRecommendedContent() }
    
    // 推荐类型标签页
    var selectedTabIndex by remember { mutableIntStateOf(0) }
    val tabs = listOf(
        RecommendationTab("个性推荐", Icons.Default.Lightbulb),
        RecommendationTab("热门内容", Icons.Default.Whatshot),
        RecommendationTab("新内容", Icons.Default.NewReleases)
    )
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("为你推荐") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
        ) {
            // 推荐类型选择器
            TabRow(
                selectedTabIndex = selectedTabIndex,
                containerColor = MaterialTheme.colorScheme.background
            ) {
                tabs.forEachIndexed { index, tab ->
                    Tab(
                        selected = selectedTabIndex == index,
                        onClick = { selectedTabIndex = index },
                        text = { Text(tab.title) },
                        icon = {
                            Icon(
                                imageVector = tab.icon,
                                contentDescription = null,
                                modifier = Modifier.size(20.dp)
                            )
                        }
                    )
                }
            }
            
            // 兴趣标签选择器
            InterestTagsSection(
                onTagSelected = { /* 根据标签过滤推荐内容 */ }
            )
            
            // 推荐内容列表
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 16.dp)
            ) {
                // 根据选中的标签页显示不同类型的推荐内容
                val filteredContent = when(selectedTabIndex) {
                    0 -> recommendedContent.filter { it.recommendationType == RecommendationType.PERSONALIZED }
                    1 -> recommendedContent.filter { it.recommendationType == RecommendationType.POPULAR }
                    2 -> recommendedContent.filter { it.recommendationType == RecommendationType.NEW }
                    else -> recommendedContent
                }
                
                items(filteredContent) { content ->
                    RecommendedContentItem(
                        content = content,
                        onContentClick = {
                            when (content.contentType) {
                                ContentType.POST -> onNavigateToPostDetail(content.id)
                                ContentType.TOPIC -> onNavigateToTopic(content.id)
                                ContentType.USER -> onNavigateToUserProfile(content.id)
                            }
                        },
                        onUserClick = { onNavigateToUserProfile(content.authorId) }
                    )
                    
                    Divider(modifier = Modifier.padding(vertical = 8.dp))
                }
            }
        }
    }
}

/**
 * 兴趣标签部分
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun InterestTagsSection(
    onTagSelected: (String) -> Unit
) {
    val interestTags = remember {
        listOf("科技", "旅行", "美食", "电影", "音乐", "健身", "摄影", "阅读", "游戏", "时尚")
    }
    
    var selectedTagIndex by remember { mutableIntStateOf(-1) }
    
    LazyRow(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp),
        contentPadding = PaddingValues(horizontal = 16.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        items(interestTags.size) { index ->
            FilterChip(
                selected = selectedTagIndex == index,
                onClick = {
                    selectedTagIndex = if (selectedTagIndex == index) -1 else index
                    onTagSelected(interestTags[index])
                },
                label = { Text(interestTags[index]) },
                leadingIcon = if (selectedTagIndex == index) {
                    {
                        Icon(
                            imageVector = Icons.Default.Star,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                    }
                } else null
            )
        }
    }
}

/**
 * 推荐内容项
 */
@Composable
private fun RecommendedContentItem(
    content: RecommendedContent,
    onContentClick: () -> Unit,
    onUserClick: () -> Unit
) {
    var isLiked by remember { mutableStateOf(content.isLiked) }
    var isBookmarked by remember { mutableStateOf(false) }
    
    ElevatedCard(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
            .clickable(onClick = onContentClick),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            // 推荐原因标签
            RecommendationReasonChip(content.recommendationReason)
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 用户信息
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .clip(CircleShape)
                        .background(getColorForName(content.authorName))
                        .clickable(onClick = onUserClick),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = content.authorName.first().toString(),
                        color = Color.White,
                        style = MaterialTheme.typography.bodyLarge
                    )
                }
                
                Column(
                    modifier = Modifier
                        .weight(1f)
                        .padding(horizontal = 8.dp)
                        .clickable(onClick = onUserClick)
                ) {
                    Text(
                        text = content.authorName,
                        style = MaterialTheme.typography.bodyLarge,
                        fontWeight = FontWeight.Bold
                    )
                    
                    Text(
                        text = content.timestamp,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
                
                if (content.contentType == ContentType.TOPIC) {
                    @OptIn(ExperimentalMaterialApi::class)
                    Chip(
                        onClick = onContentClick,
                        colors = ChipDefaults.chipColors(
                            backgroundColor = MaterialTheme.colorScheme.secondaryContainer,
                            contentColor = MaterialTheme.colorScheme.onSecondaryContainer
                        ),
                        modifier = Modifier.padding(4.dp)
                    ) {
                        Text(
                            text = "#${content.title}",
                            style = MaterialTheme.typography.bodySmall,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
            }
            
            // 内容标题和描述
            Spacer(modifier = Modifier.height(8.dp))
            
            if (content.title.isNotEmpty() && content.contentType != ContentType.TOPIC) {
                Text(
                    text = content.title,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                Spacer(modifier = Modifier.height(4.dp))
            }
            
            Text(
                text = content.content,
                style = MaterialTheme.typography.bodyMedium,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            
            // 交互按钮
            Spacer(modifier = Modifier.height(8.dp))
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                IconButton(onClick = { isLiked = !isLiked }) {
                    Icon(
                        imageVector = if (isLiked) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                        contentDescription = "点赞",
                        tint = if (isLiked) Color.Red else MaterialTheme.colorScheme.onSurface
                    )
                }
                
                IconButton(onClick = { /* 评论 */ }) {
                    Icon(
                        imageVector = Icons.Outlined.Comment,
                        contentDescription = "评论"
                    )
                }
                
                IconButton(onClick = { /* 分享 */ }) {
                    Icon(
                        imageVector = Icons.Outlined.Share,
                        contentDescription = "分享"
                    )
                }
                
                IconButton(onClick = { isBookmarked = !isBookmarked }) {
                    Icon(
                        imageVector = if (isBookmarked) Icons.Default.Bookmark else Icons.Default.BookmarkBorder,
                        contentDescription = "收藏"
                    )
                }
            }
            
            // 统计信息
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Text(
                    text = "${content.likes + (if (isLiked) 1 else 0)} 赞",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.outline
                )
                
                Text(
                    text = "${content.comments} 评论",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.outline
                )
                
                if (content.contentType == ContentType.TOPIC) {
                    Text(
                        text = "${content.participants} 参与",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
            }
        }
    }
}

/**
 * 推荐原因标签
 */
@Composable
private fun RecommendationReasonChip(reason: RecommendationReason) {
    val (color, icon, text) = when (reason) {
        RecommendationReason.SIMILAR_INTERESTS -> Triple(
            MaterialTheme.colorScheme.primaryContainer,
            Icons.Default.Lightbulb,
            "根据你的兴趣"
        )
        RecommendationReason.TRENDING -> Triple(
            MaterialTheme.colorScheme.secondaryContainer,
            Icons.Default.Whatshot,
            "热门内容"
        )
        RecommendationReason.FOLLOWED_USER -> Triple(
            MaterialTheme.colorScheme.tertiaryContainer,
            Icons.Default.Star,
            "你关注的用户"
        )
        RecommendationReason.HIGHLY_RATED -> Triple(
            MaterialTheme.colorScheme.errorContainer,
            Icons.Default.EmojiEvents,
            "高评分内容"
        )
        RecommendationReason.NEW_FOR_YOU -> Triple(
            MaterialTheme.colorScheme.surfaceVariant,
            Icons.Default.NewReleases,
            "新内容"
        )
        RecommendationReason.LOCAL_TRENDING -> Triple(
            MaterialTheme.colorScheme.secondaryContainer,
            Icons.Default.LocalFireDepartment,
            "本地热门"
        )
    }
    
    Row(
        modifier = Modifier
            .clip(RoundedCornerShape(16.dp))
            .background(color)
            .padding(horizontal = 8.dp, vertical = 4.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            modifier = Modifier.size(14.dp),
            tint = MaterialTheme.colorScheme.onSecondaryContainer
        )
        
        Spacer(modifier = Modifier.width(4.dp))
        
        Text(
            text = text,
            style = MaterialTheme.typography.labelSmall,
            color = MaterialTheme.colorScheme.onSecondaryContainer
        )
    }
}

/**
 * 根据名称生成一个固定的颜色
 */
private fun getColorForName(name: String): Color {
    val colors = listOf(
        Color(0xFF6200EA), // 深紫色
        Color(0xFF2962FF), // 深蓝色
        Color(0xFF00BFA5), // 青色
        Color(0xFFFFAB00), // 琥珀色
        Color(0xFFD50000)  // 红色
    )
    
    return colors[name.hashCode().mod(colors.size).absoluteValue]
}

/**
 * 推荐标签页数据类
 */
data class RecommendationTab(
    val title: String,
    val icon: ImageVector
)

/**
 * 内容类型枚举
 */
enum class ContentType {
    POST, // 动态
    TOPIC, // 话题
    USER // 用户
}

/**
 * 推荐类型枚举
 */
enum class RecommendationType {
    PERSONALIZED, // 个性化推荐
    POPULAR, // 热门内容
    NEW // 新内容
}

/**
 * 推荐原因枚举
 */
enum class RecommendationReason {
    SIMILAR_INTERESTS, // 基于相似兴趣
    TRENDING, // 热门趋势
    FOLLOWED_USER, // 来自关注的用户
    HIGHLY_RATED, // 高评分内容
    NEW_FOR_YOU, // 新内容
    LOCAL_TRENDING // 本地热门
}

/**
 * 推荐内容数据类
 */
data class RecommendedContent(
    val id: String,
    val contentType: ContentType,
    val title: String,
    val content: String,
    val authorId: String,
    val authorName: String,
    val timestamp: String,
    val likes: Int,
    val comments: Int,
    val participants: Int = 0,
    val recommendationType: RecommendationType,
    val recommendationReason: RecommendationReason,
    val isLiked: Boolean = false
)

/**
 * 生成示例推荐内容
 */
private fun generateRecommendedContent(): List<RecommendedContent> {
    val random = Random(System.currentTimeMillis())
    val recommendations = mutableListOf<RecommendedContent>()
    
    // 生成动态推荐
    val postContents = listOf(
        "刚体验了新开的那家火锅店，味道真的很不错！尤其是他们家的底料，香而不腻，强烈推荐大家去试试。",
        "分享一个我最近在用的学习方法，叫做'番茄工作法'，每25分钟专注学习，然后休息5分钟。简单但是非常有效！",
        "最近读完了《原子习惯》这本书，里面关于如何建立和改变习惯的方法非常实用。推荐给正在努力改变自己的朋友们。",
        "今天去爬了华山，风景真的太美了！虽然很累，但是到达山顶那一刻，所有的疲惫都值得了。",
        "刚刚看完电影《星际穿越》，被剧情深深打动，特别是父女之间跨越时空的爱，真是催人泪下。"
    )
    
    for (i in 0 until 5) {
        recommendations.add(
            RecommendedContent(
                id = "post-$i",
                contentType = ContentType.POST,
                title = "",
                content = postContents[i],
                authorId = "user-$i",
                authorName = listOf("张三", "李四", "王五", "赵六", "钱七")[i],
                timestamp = listOf("10分钟前", "30分钟前", "1小时前", "3小时前", "昨天")[i],
                likes = random.nextInt(5, 200),
                comments = random.nextInt(0, 50),
                recommendationType = when (i % 3) {
                    0 -> RecommendationType.PERSONALIZED
                    1 -> RecommendationType.POPULAR
                    else -> RecommendationType.NEW
                },
                recommendationReason = when (i % 6) {
                    0 -> RecommendationReason.SIMILAR_INTERESTS
                    1 -> RecommendationReason.TRENDING
                    2 -> RecommendationReason.FOLLOWED_USER
                    3 -> RecommendationReason.HIGHLY_RATED
                    4 -> RecommendationReason.NEW_FOR_YOU
                    else -> RecommendationReason.LOCAL_TRENDING
                },
                isLiked = random.nextBoolean()
            )
        )
    }
    
    // 生成话题推荐
    val topicNames = listOf("科技创新", "健康生活", "旅行探险", "美食分享", "读书心得")
    val topicContents = listOf(
        "关注最新科技动态，分享创新产品和技术趋势的话题。",
        "探讨健康饮食、运动健身和心理健康的综合性话题。",
        "分享旅行经历、探险故事和各地风土人情。",
        "交流美食制作心得，分享各地特色菜品和餐厅推荐。",
        "讨论各类书籍，分享读书笔记和心得体会。"
    )
    
    for (i in 0 until 5) {
        recommendations.add(
            RecommendedContent(
                id = "topic-$i",
                contentType = ContentType.TOPIC,
                title = topicNames[i],
                content = topicContents[i],
                authorId = "system",
                authorName = "官方话题",
                timestamp = "持续更新中",
                likes = random.nextInt(500, 5000),
                comments = random.nextInt(100, 1000),
                participants = random.nextInt(1000, 10000),
                recommendationType = when (i % 3) {
                    0 -> RecommendationType.PERSONALIZED
                    1 -> RecommendationType.POPULAR
                    else -> RecommendationType.NEW
                },
                recommendationReason = when (i % 6) {
                    0 -> RecommendationReason.SIMILAR_INTERESTS
                    1 -> RecommendationReason.TRENDING
                    2 -> RecommendationReason.FOLLOWED_USER
                    3 -> RecommendationReason.HIGHLY_RATED
                    4 -> RecommendationReason.NEW_FOR_YOU
                    else -> RecommendationReason.LOCAL_TRENDING
                }
            )
        )
    }
    
    // 排序以混合不同类型的内容
    return recommendations.shuffled(random)
} 